package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.MyFileAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.ActivityVideoBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class VideoActivity extends BaseAc<ActivityVideoBinding> {

    private List<MyFileBean> listShow = new ArrayList<>();
    private MyFileAdapter fileAdapter;
    private Dialog myDeleteDialog, myMoreDialog, myRenameDialog;
    private EditText dialogRename;
    private String selPath = "";

    @Override
    protected int onCreate() {
        return R.layout.activity_video;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fileAdapter = new MyFileAdapter();
        mDataBinding.rvVideoList.setAdapter(fileAdapter);
        fileAdapter.addChildClickViewIds(R.id.ivMyFileItemMore);
        fileAdapter.setOnItemChildClickListener(this);
        //更多弹框
        moreDialog();
        //重命名弹框
        renameDialog();
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvDialogMoreCancel://取消
                myMoreDialog.dismiss();
                break;
            case R.id.tvDialogMoreRename://重命名
                myMoreDialog.dismiss();
                dialogRename.setText("");
                myRenameDialog.show();
                break;
            case R.id.tvDialogRenameRight:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (Environment.isExternalStorageManager()) {
                        renameFile();
                    } else {
                        try {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, 100);
                        } catch (Exception e) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                            startActivityForResult(intent, 100);
                        }
                    }
                } else {
                    renameFile();
                }
                break;
            case R.id.tvDialogMoreShare://分享
                myMoreDialog.dismiss();
                IntentUtil.shareFile(mContext, selPath);
                break;
            case R.id.tvDialogRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogMoreDelete://删除
                myMoreDialog.dismiss();
                myDeleteDialog.show();
                break;
            case R.id.tvDialogDeleteRight:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (Environment.isExternalStorageManager()) {
                        deleteFile();
                    } else {
                        try {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, 100);
                        } catch (Exception e) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                            startActivityForResult(intent, 100);
                        }
                    }
                } else {
                    deleteFile();
                }
                break;
            case R.id.tvDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivMyFileItemMore:
                selPath = fileAdapter.getItem(position).getPath();
                myMoreDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    //重命名文件
    private void renameFile() {
        String newName = dialogRename.getText().toString();
        if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_file_name);
            return;
        }
        myRenameDialog.dismiss();
        showDialog(getString(R.string.rename_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String suffix = selPath.substring(selPath.lastIndexOf("."));
                FileUtils.rename(selPath, newName + suffix);
                String newFilePath = FileUtils.getDirName(selPath + newName + suffix);
                emitter.onNext(newFilePath);
            }

            @Override
            public void accept(String path) {
//                refreshData(path);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        getData();
                    }
                }, 2000);
            }
        });
    }

    //通知系统刷新getContentResolver
    private void refreshData(String path) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, new File(path).getAbsolutePath());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis() + "");
        getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + new File(path).getAbsolutePath())));
    }

    //删除
    private void deleteFile() {
        myDeleteDialog.dismiss();
        showDialog(getString(R.string.delete_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                mContext.getContentResolver()
                        .delete(getUri(selPath), null, null);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取path的对应uri
    private Uri getUri(String path) {
        String uriStr = "";
        for (MyFileBean bean : fileAdapter.getValidData()) {
            if (bean.getPath().equals(path)) {
                uriStr = bean.getUri();
            }
        }
        return Uri.parse(uriStr);
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_all_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }
                })
                .request();
    }

    //获取视频数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    for (SelectMediaEntity bean : selectMediaEntities) {
                        listShow.add(new MyFileBean(bean.getMediaName(), bean.getPath(), bean.getUri()
                                , ConvertUtils.byte2FitMemorySize(bean.getSize(), 3)
                                , TimeUtils.millis2String(FileUtils.getFileLastModified(bean.getPath()), "yyyy年MM月dd日"), 1, false));
                    }
                }
                if (listShow.size() > 0) {
                    fileAdapter.setList(listShow);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.llVideoNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.llVideoNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //更多弹框
    private void moreDialog() {
        myMoreDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_more, null);
        myMoreDialog.setContentView(inflate);
        myMoreDialog.setCancelable(true);
        Window dialogWindow = myMoreDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView rename = inflate.findViewById(R.id.tvDialogMoreRename);
        TextView share = inflate.findViewById(R.id.tvDialogMoreShare);
        TextView delete = inflate.findViewById(R.id.tvDialogMoreDelete);
        TextView cancel = inflate.findViewById(R.id.tvDialogMoreCancel);
        rename.setOnClickListener(this);
        share.setOnClickListener(this);
        delete.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameRight);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.85);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView title = inflate.findViewById(R.id.tvDialogDeleteTitle);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteRight);
        title.setText(getString(R.string.del_title));
        tip.setText(getString(R.string.del_tip));
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}